package com.cy.pj.sys.realm;

import java.util.UUID;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cy.pj.sys.dao.SysMemberDao;
import com.cy.pj.sys.entity.SysMember;

// Credentials:资格证书
@Service
public class ShiroUserRealm extends AuthorizingRealm{

	@Autowired
	private SysMemberDao sysMemberDao;

	// 构建凭证匹配器
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		// 构建对象
		HashedCredentialsMatcher cMacher = new HashedCredentialsMatcher();
		// 设置加密算法
		cMacher.setHashAlgorithmName("MD5");
		// 设置加密次数
		cMacher.setHashIterations(1);
		super.setCredentialsMatcher(cMacher);
	}


	// 主要返回一个realm对象
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) 
			throws AuthenticationException {
		// 获取用户名
		UsernamePasswordToken uToken= (UsernamePasswordToken) token;
		String memberName = uToken.getUsername();
		// 基于用户名做查询操作
		SysMember member = sysMemberDao.findMemberByMemberName(memberName);
		// 对结果进行判断
		if(member==null)
			throw new UnknownAccountException();
		// 封装用户信息
		ByteSource salt = ByteSource.Util.bytes(member.getSalt());
		SimpleAuthenticationInfo realm = new SimpleAuthenticationInfo(
				member, 
				member.getPassword(), 
				salt, 
				getName());
		// 返回封装信息
		return realm;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		return null;
	}

	
	

}





















